from machine import UART
import time
import _thread

def demo():
    # 初始化UART对象，例如连接到硬件串口0
    uart = UART(2, baudrate=9600) #2表示485
    uart.init(baudrate=115200, bits=8, parity=None, stop=1)
    # 定义数据发送和接收处理函数
    def send_data():
        data_to_send = "Hello, MicroPython UART!".encode('utf-8')
        uart.write(data_to_send)  # 发送数据
        print("Sent:", data_to_send)

    def receive_data():
        while True:
            if uart.any():  # 检查是否有可用的数据
                buf = bytearray(10)  # 创建缓冲区
                time.sleep_ms(100)
                n_r = uart.read()
                print("Recei:", n_r)  # 打印接收到的原始字节数据
                n_read = uart.readinto(buf)  # 尝试读取最多100字节到缓冲区
                print("Received:", n_read)  # 打印接收到的原始字节数据长度
                print("Received:", buf)  # 打印接收到的原始字节数据
                line = uart.readline()  # 读取一行文本数据
                print("Line received:", line)

    _thread.start_new_thread(receive_data,())
    try:
        while True:
            send_data()  # 定期发送数据
            time.sleep(5)  # 延时5秒后再发送

    except KeyboardInterrupt:
        print("User interrupted, deinitializing UART...")
        uart.sendbreak()
        uart.deinit()  # 清理资源，关闭UART


if __name__ == '__main__':
    demo()


